from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from loguru import logger
from rest_framework.views import APIView
from rest_framework.request import Request
import requests,socket
from datetime import datetime,timedelta

from op_drf.response import SuccessResponse, ErrorResponse
from .handler import set_password
from .models import *
from op_drf.viewsets import CustomModelViewSet
from .serializers import *
from op_drf.request_util import (
                get_request_ip,
                get_os,
                get_browser,
                get_login_location,
            )

# Create your views here.

def login(request):
    username = request.GET.get("username",'')
    logger.debug(username)
    context = {"username":username}
    user_id = request.session.get("userid", None)
    if user_id:
        return HttpResponseRedirect('/index')
    return render(request, 'login.html', context)

def logout(request):
    user_id = request.session.get("userid", None)
    LoginHistory.objects.filter(loginstatus=True, user__id=user_id).update(loginstatus=False)
    # loginhistory = LoginHistory.objects.filter(loginstatus=True,user__id=user_id)
    # if loginhistory:
    #     loginhistory_obj = loginhistory[0]
    #     loginhistory_obj.loginstatus = 0
    #     loginhistory_obj.save()
    request.session.clear()
    return redirect("/login")

def register(request):
    context = {}
    return render(request, 'register.html', context)

class StarUserViewSet(CustomModelViewSet):
    queryset = StarUser.objects.exclude(id=1)
    # logger.debug("success")
    serializer_class = ReadStarUserSerializer
    create_serializer_class = WriteStarUserSerializer
    # filter_class = UserFilter
    pagination_class = None
    search_fields = ("username", "fullname")

    ordering = ["-id"]

    def create(self, request: Request, *args, **kwargs):
        """
        重写create方法，在创建阶段的时候，推送新增的阶段到协同系统中。
        """
        logger.debug("前端传入的数据： %s" % request.data)
        logger.debug("请求携带的数据： %s" % kwargs)
        username = request.data["username"]
        pwd = request.data["pwd"]
        staruser = StarUser.objects.filter(is_delete=False,username=username)
        if not staruser:
            serializer = self.create_serializer_class(data=request.data)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            logger.debug(serializer.data)
            id = serializer.data.get("id",None)
            logger.debug(id)
            staruser = StarUser.objects.get(pk=id)
            staruser.pwd = set_password(pwd)
            staruser.save()
            return SuccessResponse(msg="注册成功", data=serializer.data)
        else:
            return ErrorResponse(msg="注册失败，该用户名已存在!")

    def change_pwd(self, request: Request, *args, **kwargs):
        logger.debug(request.data)
        staruser = StarUser.objects.filter(is_delete=False,id=request.data["user_id"])
        if staruser:
            staruser_obj = staruser[0]
            if not staruser_obj.pwd == set_password(request.data.get("old_pwd",None)):
                return ErrorResponse(msg="原密码错误")

            staruser_obj.pwd = set_password(request.data.get("new_pwd",None))
            staruser_obj.save()
            request.session.clear()

        return SuccessResponse(msg="修改成功!")


class LoginHistoryViewSet(CustomModelViewSet):
    queryset = LoginHistory.objects.all()
    serializer_class = ReadLoginHistorySerializer
    create_serializer_class = WriteLoginHistorySerializer
    pagination_class = None
    search_fields = ("username", "fullname")

    ordering = ["-id"]

    def create(self, request: Request, *args, **kwargs):
        """
        重写create方法，在创建阶段的时候，推送新增的阶段到协同系统中。
        """

        # request.data["loginip"]=get_request_ip(request)

        logger.debug("前端传入的数据： %s" % request.data)
        logger.debug("请求携带的数据： %s" % kwargs)
        username = request.data["username"]
        pwd = request.data["pwd"]
        staruser = StarUser.objects.filter(is_delete=False,username=username)
        if not staruser:
            return ErrorResponse(msg="登录失败，该用户名不存在!")
        else:
            logger.debug(pwd)
            logger.debug(set_password(pwd))
            if not staruser[0].pwd == set_password(pwd):
                return ErrorResponse(msg="登录失败，密码错误!")


            serializer = self.create_serializer_class(data=request.data)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            # 保存登录信息
            user_id = serializer.data.get("user",None)
            # 保留session
            request.session["userid"] = user_id
            # 默认过期时间,采用默认的过期时间，不进行设置
            # request.session.set_expiry(1*60)
            id = serializer.data.get("id",None)
            if id:
                loginhistory = LoginHistory.objects.get(pk=id)
                loginhistory.loginip = get_request_ip(request)
                loginhistory.loginaddress = get_login_location(request,loginhistory.loginip)
                loginhistory.loginos = get_os(request)
                loginhistory.save()
            return SuccessResponse(msg="登录成功", data=serializer.data)

